package com.xjscrm.console.service.customer.groupPull.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupRule;
import com.xjscrm.common.vo.grouppull.GroupRuleInfo;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.groupPull.*;
import com.xjscrm.console.param.groupSend.UpdateSleepRuleDto;
import com.xjscrm.console.param.operatePlan.EffectuateGroupDto;
import com.xjscrm.console.param.wwCustomer.CustomerQuery;
import com.xjscrm.console.param.wwCustomer.CustomerTagQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.groupPull.GroupPullTaskService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import com.xjscrm.console.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupPullTaskServiceImpl implements GroupPullTaskService {

    @Autowired
  private GroupPullTaskMapper groupPullTaskMapper;

    @Autowired
    private GroupPullTaskDeviceMapper groupPullTaskDeviceMapper;

    @Autowired
    private GroupPullTaskCustomerMapper groupPullTaskCustomerMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private GroupPullJobMapper groupPullJobMapper;

    @Autowired
    private GroupPullJobDeviceMapper groupPullJobDeviceMapper;

    @Autowired
    private GroupPullJobMsgMapper groupPullJobMsgMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Autowired
    private WwDeviceService wwDeviceService;

    @Autowired
    private GroupPullTaskDeviceConfigMapper groupPullTaskDeviceConfigMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;

//    @Autowired
//    private WwTagsMapper wwTagsMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGroupPullTask(GroupPullTaskDto groupPullTaskDto) {
        if(groupPullTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullTaskDto.getGroupPullTaskDeviceDtoList()==null||groupPullTaskDto.getGroupPullTaskDeviceDtoList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //保存群发任务
        GroupPullTask groupPullTask = new GroupPullTask();
        BeanUtil.copyProperties(groupPullTaskDto,groupPullTask);
        //设置拉群规则
        if(groupPullTaskDto.getGroupPullData()!=null){
            groupPullTask.setRule(JSONObject.toJSONString(groupPullTaskDto.getGroupPullData()));
        }
        //设置引导语
        if(groupPullTaskDto.getGroupPullDataList()!=null&&!groupPullTaskDto.getGroupPullDataList().isEmpty()){
            groupPullTask.setGuider(JSONObject.toJSONString(groupPullTaskDto.getGroupPullDataList()));
        }
        //保存拉群任务
        int time = DateUtil.getTime();
        long id = IdWorker.getId();
        groupPullTask.setId(id);
        groupPullTask.setCreateTime(time);
        groupPullTask.setUpdateTime(time);
        groupPullTaskMapper.insert(groupPullTask);

        //保存拉群任务和机器人关系
        for (GroupPullTaskDeviceDto groupPullTaskDeviceDto:groupPullTaskDto.getGroupPullTaskDeviceDtoList()) {
            GroupPullTaskDevice groupPullTaskDevice=new GroupPullTaskDevice();
            BeanUtil.copyProperties(groupPullTaskDeviceDto,groupPullTaskDevice);
            groupPullTaskDevice.setTaskId(id);
            groupPullTaskDevice.setMerId(groupPullTask.getMerId());
            groupPullTaskDeviceMapper.add(groupPullTaskDevice);
        }

        //选择具体客户时，需要存入客户拉群任务和客户关系
        if(groupPullTaskDto.getGroupPullTaskCustomerDtoList()!=null&&!groupPullTaskDto.getGroupPullTaskCustomerDtoList().isEmpty()){

            for (GroupPullTaskCustomerDto groupPullTaskCustomerDto:groupPullTaskDto.getGroupPullTaskCustomerDtoList()) {
                GroupPullTaskCustomer groupPullTaskCustomer=new GroupPullTaskCustomer();
                BeanUtil.copyProperties(groupPullTaskCustomerDto,groupPullTaskCustomer);
                groupPullTaskCustomer.setTaskId(id);
                groupPullTaskCustomer.setMerId(groupPullTask.getMerId());
                groupPullTaskCustomerMapper.add(groupPullTaskCustomer);
            }
        }
    }

    @Override
    public Object getGroupPullTaskList(GroupPullTaskQuery groupPullTaskQuery) {
        if(groupPullTaskQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String orderBy = OrderByUtil.getOrderBy(groupPullTaskQuery.getOrderByField(), groupPullTaskQuery.isAsc());
        PageHelper.startPage(groupPullTaskQuery.getCurrent(),groupPullTaskQuery.getSize(),orderBy);

        List<GroupPullTaskVo> groupPullTaskVoList=groupPullTaskMapper.getGroupPullTaskList(groupPullTaskQuery);

        if(groupPullTaskVoList!=null&&!groupPullTaskVoList.isEmpty()){
            groupPullTaskVoList.forEach(it->{
                //获取关联的机器人ID
                GroupPullDeviceQuery groupPullDeviceQuery=new GroupPullDeviceQuery();
                groupPullDeviceQuery.setMerId(it.getMerId());
                groupPullDeviceQuery.setTaskId(it.getId());
                List<GroupPullTaskDeviceVo> groupPullTaskDeviceList= groupPullTaskDeviceMapper.getGroupPullTaskDeviceList(groupPullDeviceQuery);
                if(groupPullTaskDeviceList!=null&&!groupPullTaskDeviceList.isEmpty()){
                    List<Long> deviceUniqueIds = groupPullTaskDeviceList.stream().map(GroupPullTaskDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
                    //获取关联机器人的昵称
                    WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
                    wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                    wwDeviceQuery.setMerId(it.getMerId());
                    List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
                    if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                        List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                        it.setDeviceNames(deviceNames);
                    }
                }
            });
        }
        return new MyPageInfo<>(groupPullTaskVoList);
    }

    @Override
    public Object getGroupPullTaskDetail(GroupPullTaskDto groupPullTaskDto) {
        if(groupPullTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullTaskDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        GroupPullTask groupPullTask= groupPullTaskMapper.getById(groupPullTaskDto.getId(),groupPullTaskDto.getMerId());
        if(groupPullTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该任务");
        }

        GroupPullTaskVo groupPullTaskVo=new GroupPullTaskVo();
        BeanUtil.copyProperties(groupPullTask,groupPullTaskVo);

        //设置拉群规则
        if(!StringUtils.isBlank(groupPullTaskVo.getRule())){
            groupPullTaskVo.setGroupPullData(JSONObject.parseObject(groupPullTaskVo.getRule(),GroupPullData.class));
        }
        //设置引导语
        if(!StringUtils.isBlank(groupPullTaskVo.getGuider())){
            groupPullTaskVo.setGroupPullDataList(JSONObject.parseArray(groupPullTaskVo.getGuider(),GroupPullData.class));
        }


        //获取关联的机器人ID
        GroupPullDeviceQuery groupPullDeviceQuery=new GroupPullDeviceQuery();
        groupPullDeviceQuery.setMerId(groupPullTaskVo.getMerId());
        groupPullDeviceQuery.setTaskId(groupPullTaskVo.getId());
        List<GroupPullTaskDeviceVo> groupPullTaskDeviceList= groupPullTaskDeviceMapper.getGroupPullTaskDeviceList(groupPullDeviceQuery);
        if(groupPullTaskDeviceList!=null&&!groupPullTaskDeviceList.isEmpty()){
            List<Long> deviceUniqueIds = groupPullTaskDeviceList.stream().map(GroupPullTaskDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
            //获取关联机器人的昵称
            WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
            wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
            wwDeviceQuery.setMerId(groupPullTaskVo.getMerId());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                List<String> deviceNames = wwDeviceList.stream().map(WwDeviceVo::getDeviceName).distinct().collect(Collectors.toList());
                groupPullTaskVo.setDeviceNames(deviceNames);
            }

            for (GroupPullTaskDeviceVo groupPullTaskDeviceVo:groupPullTaskDeviceList) {
                WwDevice wwDevice = wwDeviceMapper.getById(groupPullTaskDeviceVo.getDeviceUniqueId(), groupPullTaskVo.getMerId());
                if(wwDevice!=null){
                    groupPullTaskDeviceVo.setDeviceName(wwDevice.getDeviceName());
                    groupPullTaskDeviceVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                }
            }
            groupPullTaskVo.setGroupPullTaskDeviceVoList(groupPullTaskDeviceList);
        }

        //获取客户
        GroupPullTaskCustomerQuery groupPullTaskCustomerQuery=new GroupPullTaskCustomerQuery();
        groupPullTaskCustomerQuery.setMerId(groupPullTask.getMerId());
        groupPullTaskCustomerQuery.setTaskId(groupPullTask.getId());
        List<GroupPullTaskCustomerVo> groupPullTaskCustomerVoList = groupPullTaskCustomerMapper.getGroupPullTaskCustomerList(groupPullTaskCustomerQuery);
        if(groupPullTaskCustomerVoList!=null&&!groupPullTaskCustomerVoList.isEmpty()){
//            wxids = groupPullTaskCustomerVoList.stream().map(GroupPullTaskCustomerVo::getWxid).distinct().collect(Collectors.toList());
            List<WwCustomerVo> wwCustomerVoList=new ArrayList<>();
            for (GroupPullTaskCustomerVo groupPullTaskCustomerVo:groupPullTaskCustomerVoList) {
                try {

                    WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(groupPullTaskCustomerVo.getWxid(), groupPullTaskCustomerVo.getDeviceUniqueId(), groupPullTask.getMerId());
                    if(wwCustomer!=null){
                        WwCustomerVo wwCustomerVo = new WwCustomerVo();
                        BeanUtil.copyProperties(wwCustomer,wwCustomerVo);

                        WwDevice wwDevice = wwDeviceMapper.getById(wwCustomer.getDeviceUniqueId(), wwCustomer.getMerId());
                        if(wwDevice!=null){
                            wwCustomerVo.setDeviceName(wwDevice.getDeviceName());
                            wwCustomerVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                        }
                        wwCustomerVoList.add(wwCustomerVo);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            groupPullTaskVo.setWwCustomerVoList(wwCustomerVoList);
        }

        //获取客户
//        if(wxids!=null&&!wxids.isEmpty()){
//            CustomerQuery customerQuery=new CustomerQuery();
//            customerQuery.setMerId(groupPullTask.getMerId());
//            customerQuery.setWxids(wxids);
//            List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
//            if(wwCustomerVoList!=null&&!wwCustomerVoList.isEmpty()){
//                wwCustomerVoList.forEach(it->{
//                    WwDevice wwDevice = wwDeviceMapper.getById(it.getDeviceUniqueId(), it.getMerId());
//                    if(wwDevice!=null){
//                        it.setDeviceName(wwDevice.getDeviceName());
//                        it.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
//                    }
//                });
//                groupPullTaskVo.setWwCustomerVoList(wwCustomerVoList);
//            }
//
//        }

//        //获取企业标签列表
//        if(!org.apache.commons.lang3.StringUtils.isBlank(groupPullTaskVo.getCustomerEnterpriseTags())){
//            ObjectMapper objectMapper=new ObjectMapper();
//            try {
//                List<Long> list = objectMapper.readValue(groupPullTaskVo.getCustomerEnterpriseTags(),new TypeReference<List<Long>>(){});
//                CustomerTagQuery customerTagQuery=new CustomerTagQuery();
//                customerTagQuery.setTagIds(list);
//                customerTagQuery.setMerId(groupPullTask.getMerId());
//                List<WwTags> customerTag = wwTagsMapper.getCustomerTag(customerTagQuery);
//                if(customerTag!=null){
//                    groupPullTaskVo.setWwTagsList(customerTag);
//                }
//            } catch (JsonProcessingException e) {
//                throw new RuntimeException(e);
//            }
//
//        }

        return groupPullTaskVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroupPullTask(GroupPullTaskDto groupPullTaskDto) {
        if(groupPullTaskDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(groupPullTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullTaskDto.getGroupPullTaskDeviceDtoList()==null||groupPullTaskDto.getGroupPullTaskDeviceDtoList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(groupPullTaskDto.getType()==null||groupPullTaskDto.getType()==0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "立即发送类型不支持编辑");
        }

        GroupPullTask groupPullTask= groupPullTaskMapper.getById(groupPullTaskDto.getId(),groupPullTaskDto.getMerId());
        if(groupPullTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该任务");
        }

        BeanUtil.copyProperties(groupPullTaskDto,groupPullTask);
        groupPullTaskMapper.update(groupPullTask);
        //设置拉群规则
        if(groupPullTaskDto.getGroupPullData()!=null){

            GroupPullData groupPullData=JSONObject.parseObject(groupPullTask.getRule(),GroupPullData.class);
            //创建新群名称开始编号 重制后清除缓存
            if(groupPullData!=null&&groupPullTaskDto.getGroupPullData().getCreateGroupNameStartNo()!=null&&groupPullData.getCreateGroupNameStartNo()!=null&&!groupPullData.getCreateGroupNameStartNo().equals(groupPullTaskDto.getGroupPullData().getCreateGroupNameStartNo())){

                GroupPullDeviceQuery groupPullDeviceQuery=new GroupPullDeviceQuery();
                groupPullDeviceQuery.setTaskId(groupPullTask.getId());
                groupPullDeviceQuery.setMerId(groupPullTask.getMerId());
                List<GroupPullTaskDeviceVo> groupPullTaskDeviceList = groupPullTaskDeviceMapper.getGroupPullTaskDeviceList(groupPullDeviceQuery);
                if(groupPullTaskDeviceList!=null&&!groupPullTaskDeviceList.isEmpty()){
                    for (GroupPullTaskDeviceVo groupPullTaskDeviceVo:groupPullTaskDeviceList) {
                        try {
                            redisTemplate.delete(String.format(RedisCacheKeyEnum.GROUP_PULL_GROUP_NAME_START_NO.getKey(),groupPullData.getGroupPullKey(),groupPullTaskDeviceVo.getDeviceUniqueId()));
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            }

            groupPullTask.setRule(JSONObject.toJSONString(groupPullTaskDto.getGroupPullData()));
        }
        //设置引导语
        if(groupPullTaskDto.getGroupPullDataList()!=null&&!groupPullTaskDto.getGroupPullDataList().isEmpty()){
            groupPullTask.setGuider(JSONObject.toJSONString(groupPullTaskDto.getGroupPullDataList()));
        }

        //查询群发任务和机器人关系 删除旧数据
        GroupPullDeviceQuery groupPullDeviceQuery=new GroupPullDeviceQuery();
        groupPullDeviceQuery.setMerId(groupPullTask.getMerId());
        groupPullDeviceQuery.setTaskId(groupPullTask.getId());
        List<GroupPullTaskDeviceVo> groupPullTaskDeviceList= groupPullTaskDeviceMapper.getGroupPullTaskDeviceList(groupPullDeviceQuery);
        if(groupPullTaskDeviceList!=null&&!groupPullTaskDeviceList.isEmpty()){
            groupPullTaskDeviceList.forEach(it->groupPullTaskDeviceMapper.delById(it.getId(),it.getMerId()));
        }

        //保存拉群任务和机器人关系
        for (GroupPullTaskDeviceDto groupPullTaskDeviceDto:groupPullTaskDto.getGroupPullTaskDeviceDtoList()) {
            GroupPullTaskDevice groupPullTaskDevice=new GroupPullTaskDevice();
            BeanUtil.copyProperties(groupPullTaskDeviceDto,groupPullTaskDevice);
            groupPullTaskDevice.setTaskId(groupPullTask.getId());
            groupPullTaskDevice.setMerId(groupPullTask.getMerId());
            groupPullTaskDeviceMapper.add(groupPullTaskDevice);
        }

        //查询群发任务和客户关系 删除旧数据
        GroupPullTaskCustomerQuery groupPullTaskCustomerQuery=new GroupPullTaskCustomerQuery();
        groupPullTaskCustomerQuery.setMerId(groupPullTask.getMerId());
        groupPullTaskCustomerQuery.setTaskId(groupPullTask.getId());
        List<GroupPullTaskCustomerVo> groupPullTaskCustomerVoList = groupPullTaskCustomerMapper.getGroupPullTaskCustomerList(groupPullTaskCustomerQuery);
        if(groupPullTaskCustomerVoList!=null&&!groupPullTaskCustomerVoList.isEmpty()){
            groupPullTaskCustomerVoList.forEach(it->groupPullTaskCustomerMapper.delById(it.getId(),it.getMerId()));
        }

        //选择具体客户时，需要存入客户拉群任务和客户关系
        if(groupPullTaskDto.getGroupPullTaskCustomerDtoList()!=null&&!groupPullTaskDto.getGroupPullTaskCustomerDtoList().isEmpty()){

            for (GroupPullTaskCustomerDto groupPullTaskCustomerDto:groupPullTaskDto.getGroupPullTaskCustomerDtoList()) {
                GroupPullTaskCustomer groupPullTaskCustomer=new GroupPullTaskCustomer();
                BeanUtil.copyProperties(groupPullTaskCustomerDto,groupPullTaskCustomer);
                groupPullTaskCustomer.setTaskId(groupPullTask.getId());
                groupPullTaskCustomer.setMerId(groupPullTask.getMerId());
                groupPullTaskCustomerMapper.add(groupPullTaskCustomer);
            }
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleGroupPullTask(DelGroupPullTaskDto delGroupPullTaskDto) {
        if(delGroupPullTaskDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(delGroupPullTaskDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        GroupPullTask groupPullTask= groupPullTaskMapper.getById(delGroupPullTaskDto.getId(),delGroupPullTaskDto.getMerId());
        if(groupPullTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该任务");
        }

        //查询群发任务和机器人关系 删除旧数据
        GroupPullDeviceQuery groupPullDeviceQuery=new GroupPullDeviceQuery();
        groupPullDeviceQuery.setMerId(groupPullTask.getMerId());
        groupPullDeviceQuery.setTaskId(groupPullTask.getId());
        List<GroupPullTaskDeviceVo> groupPullTaskDeviceList= groupPullTaskDeviceMapper.getGroupPullTaskDeviceList(groupPullDeviceQuery);
        if(groupPullTaskDeviceList!=null&&!groupPullTaskDeviceList.isEmpty()){
            groupPullTaskDeviceList.forEach(it->groupPullTaskDeviceMapper.delById(it.getId(),it.getMerId()));
        }

        //查询群发任务和客户关系 删除旧数据
        GroupPullTaskCustomerQuery groupPullTaskCustomerQuery=new GroupPullTaskCustomerQuery();
        groupPullTaskCustomerQuery.setMerId(groupPullTask.getMerId());
        groupPullTaskCustomerQuery.setTaskId(groupPullTask.getId());
        List<GroupPullTaskCustomerVo> groupPullTaskCustomerVoList = groupPullTaskCustomerMapper.getGroupPullTaskCustomerList(groupPullTaskCustomerQuery);
        if(groupPullTaskCustomerVoList!=null&&!groupPullTaskCustomerVoList.isEmpty()){
            groupPullTaskCustomerVoList.forEach(it->groupPullTaskCustomerMapper.delById(it.getId(),it.getMerId()));
        }
           //删除执行记录
        if(delGroupPullTaskDto.getType()!=null&&delGroupPullTaskDto.getType()==1){

            GroupPullJobQuery groupPullJobQuery=new GroupPullJobQuery();
            groupPullJobQuery.setMerId(groupPullTask.getMerId());
            groupPullJobQuery.setTaskId(groupPullTask.getId());
            List<GroupPullJobVo> groupPullJobList = groupPullJobMapper.getGroupPullJobList(groupPullJobQuery);
            if(groupPullJobList!=null&&!groupPullJobList.isEmpty()){
                groupPullJobList.forEach(it->{

                    GroupPullJobDeviceQuery groupPullJobDeviceQuery=new GroupPullJobDeviceQuery();
                    groupPullJobDeviceQuery.setMerId(it.getMerId());
                    groupPullJobDeviceQuery.setJobId(it.getId());
                    List<GroupPullJobDeviceVo> groupPullJobDeviceList = groupPullJobDeviceMapper.getGroupPullJobDeviceList(groupPullJobDeviceQuery);
                    if(groupPullJobDeviceList!=null&&!groupPullJobDeviceList.isEmpty()){
                        groupPullJobDeviceList.forEach(item->groupPullJobDeviceMapper.delById(item.getId(),item.getMerId()));
                    }

                    GroupPullJobMsgQuery groupPullJobMsgQuery=new GroupPullJobMsgQuery();
                    groupPullJobMsgQuery.setMerId(it.getMerId());
                    groupPullJobMsgQuery.setJobId(it.getId());
                    List<GroupPullJobMsgVo> groupPullJobMsgList = groupPullJobMsgMapper.getGroupPullJobMsgList(groupPullJobMsgQuery);
                    if(groupPullJobMsgList!=null&&!groupPullJobMsgList.isEmpty()){
                        groupPullJobMsgList.forEach(item2->groupPullJobMsgMapper.delById(item2.getId(),item2.getMerId()));
                    }


                    groupPullJobMapper.deleById(it.getId(),it.getMerId());
                });
            }
        }
        //删除任务
        groupPullTaskMapper.delById(groupPullTask.getId(),groupPullTask.getMerId());
    }

    @Override
    public Object getGroupPullJobList(GroupPullJobQuery groupPullJobQuery) {
        if(groupPullJobQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(groupPullJobQuery.getOrderByField(), groupPullJobQuery.isAsc());
        PageHelper.startPage(groupPullJobQuery.getCurrent(), groupPullJobQuery.getSize(), orderBy);
        List<GroupPullJobVo> groupPullJobVoList=groupPullJobMapper.getGroupPullJobList(groupPullJobQuery);

        return new MyPageInfo<>(groupPullJobVoList);
    }

    @Override
    public Object getGroupPullJobDeviceList(GroupPullJobDeviceDto groupPullJobDeviceDto) {
        if(groupPullJobDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullJobDeviceDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupPullJobDeviceQuery groupPullJobDeviceQuery=new GroupPullJobDeviceQuery();
        groupPullJobDeviceQuery.setMerId(groupPullJobDeviceDto.getMerId());
        groupPullJobDeviceQuery.setJobId(groupPullJobDeviceDto.getId());
        List<GroupPullJobDeviceVo> groupPullJobDeviceVoList=groupPullJobDeviceMapper.getGroupPullJobDeviceList(groupPullJobDeviceQuery);

        if(groupPullJobDeviceVoList!=null&&!groupPullJobDeviceVoList.isEmpty()){
            groupPullJobDeviceVoList.forEach(it->{
                //获取机器人头像以及昵称
                WwDevice wwDevice = wwDeviceMapper.getById(it.getDeviceUniqueId(), it.getMerId());
                if(wwDevice!=null){
                    it.setDeviceName(wwDevice.getDeviceName());
                    it.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                }

                //获取发送数和总数
                GroupPullJobMsgQuery groupPullJobMsgQuery=new GroupPullJobMsgQuery();
                groupPullJobMsgQuery.setMsgTypes(Arrays.asList(101,102));
                groupPullJobMsgQuery.setMerId(it.getMerId());
                groupPullJobMsgQuery.setJobId(it.getJobId());
                groupPullJobMsgQuery.setDeviceUniqueId(it.getDeviceUniqueId());
               List<GroupPullJobMsgVo> groupPullJobMsgVoList=groupPullJobMsgMapper.getGroupPullJobMsgList(groupPullJobMsgQuery);

               it.setTotal(groupPullJobMsgVoList.size());
               it.setSend(groupPullJobMsgVoList.stream().filter(item->item.getStatus()==2).collect(Collectors.toList()).size());
            });
        }

        return groupPullJobDeviceVoList;
    }


    @Override
    public Object getGroupPullJobMsgList(GroupPullJobMsgQuery groupPullJobMsgQuery) {
        if(groupPullJobMsgQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullJobMsgQuery.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
       GroupPullJobDevice groupPullJobDevice=  groupPullJobDeviceMapper.getById(groupPullJobMsgQuery.getId(),groupPullJobMsgQuery.getMerId());
        if(groupPullJobDevice==null){
            return new MyPageInfo<>(null);
        }

        if(!StringUtils.isBlank(groupPullJobMsgQuery.getKeyword())){
            CustomerQuery customerQuery=new CustomerQuery();
            customerQuery.setKeyword(groupPullJobMsgQuery.getKeyword());
            customerQuery.setMerId(groupPullJobMsgQuery.getMerId());
            List<WwCustomerVo> wwCustomerVoList = wwCustomerMapper.getCustomer(customerQuery);
            if(wwCustomerVoList==null||wwCustomerVoList.isEmpty()){
                return new MyPageInfo<>(null);
            }
            List<String> collect = wwCustomerVoList.stream().map(WwCustomerVo::getWxid).distinct().collect(Collectors.toList());
            groupPullJobMsgQuery.setWxIds(collect);
        }

        groupPullJobMsgQuery.setMsgTypes(Arrays.asList(101,102));
        groupPullJobMsgQuery.setJobId(groupPullJobDevice.getJobId());
        groupPullJobMsgQuery.setDeviceUniqueId(groupPullJobDevice.getDeviceUniqueId());
        String orderBy = OrderByUtil.getOrderBy(groupPullJobMsgQuery.getOrderByField(), groupPullJobMsgQuery.isAsc());
        PageHelper.startPage(groupPullJobMsgQuery.getCurrent(),groupPullJobMsgQuery.getSize(),orderBy);
        List<GroupPullJobMsgVo> groupPullJobMsgVoList=groupPullJobMsgMapper.getGroupPullJobMsgList(groupPullJobMsgQuery);
        if(groupPullJobMsgVoList!=null&&!groupPullJobMsgVoList.isEmpty()){
            groupPullJobMsgVoList.forEach(it->{
                //设置客户头像和昵称
                WwCustomer wwCustomer = wwCustomerMapper.getByDeviceAndWxid(it.getSendWxid(), it.getDeviceUniqueId(), it.getMerId());
                 if(wwCustomer!=null){
                     it.setWwCustomerName(wwCustomer.getName());
                     it.setWwCustomerHeadImageUrl(wwCustomer.getHeadImgUrl());
                     it.setWwCustomerId(wwCustomer.getId());
                 }
                 //设置群名
                WwGroup wwGroup = wwGroupMapper.selectByGroupWxId(it.getMerId(), it.getDeviceUniqueId(), it.getGroupWxid());
                 if(wwGroup!=null){
                     it.setGroupName(wwGroup.getGroupName());
                 }

                 //查看客户是否入群
                WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroup.getGroupWxid(), wwCustomer.getWxid(), wwGroup.getMerId());
                 if(wwGroupMember==null){
                     it.setJoinGroupStatus(0);
                 }else {
                     it.setJoinGroupStatus(1);
                 }


            });
        }
        return new MyPageInfo<>(groupPullJobMsgVoList);
    }

    @Override
    public Object getDeviceList(WwDeviceQuery wwDeviceQuery) {
        if(wwDeviceQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        List<GroupPullTaskDeviceConfigVo> groupPullTaskDeviceConfigVoList=new ArrayList<>();

        MyPageInfo<WwDeviceVo> wwDeviceVoMyPageInfo = wwDeviceService.getWwDevice(wwDeviceQuery);
        if(wwDeviceVoMyPageInfo.getRecords()!=null&&!wwDeviceVoMyPageInfo.getRecords().isEmpty()){
            for (WwDeviceVo wwDeviceVo:wwDeviceVoMyPageInfo.getRecords()) {
                try {
                    GroupPullTaskDeviceConfigVo groupPullTaskDeviceConfigVo=new GroupPullTaskDeviceConfigVo();
                    groupPullTaskDeviceConfigVo.setDeviceUniqueId(wwDeviceVo.getId());
                    groupPullTaskDeviceConfigVo.setDeviceName(wwDeviceVo.getDeviceName());
                    groupPullTaskDeviceConfigVo.setDeviceHeaderImage(wwDeviceVo.getHeadImgUrl());
                    groupPullTaskDeviceConfigVo.setMerId(wwDeviceVo.getMerId());

                 GroupPullTaskDeviceConfig  groupPullTaskDeviceConfig=groupPullTaskDeviceConfigMapper.getByDeviceUniqueId(wwDeviceVo.getId(),wwDeviceVo.getMerId());
                 if(groupPullTaskDeviceConfig!=null){
                     groupPullTaskDeviceConfigVo.setId(groupPullTaskDeviceConfig.getId());
                     groupPullTaskDeviceConfigVo.setRateMin(groupPullTaskDeviceConfig.getRateMin());
                     groupPullTaskDeviceConfigVo.setRateMax(groupPullTaskDeviceConfig.getRateMax());
                     groupPullTaskDeviceConfigVo.setSleepRule(JSONObject.parseObject(groupPullTaskDeviceConfig.getRule(), OperatorPlanDeviceRule.class));
                 }
                    groupPullTaskDeviceConfigVoList.add(groupPullTaskDeviceConfigVo);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        MyPageInfo<GroupPullTaskDeviceConfigVo> groupPullTaskDeviceConfigVoMyPageInfo = new MyPageInfo<>(groupPullTaskDeviceConfigVoList);
        groupPullTaskDeviceConfigVoMyPageInfo.setPages(wwDeviceVoMyPageInfo.getPages());
        groupPullTaskDeviceConfigVoMyPageInfo.setTotal(wwDeviceVoMyPageInfo.getTotal());
        groupPullTaskDeviceConfigVoMyPageInfo.setSize(wwDeviceVoMyPageInfo.getSize());
        groupPullTaskDeviceConfigVoMyPageInfo.setCurrent(wwDeviceVoMyPageInfo.getCurrent());
        return groupPullTaskDeviceConfigVoMyPageInfo;
    }

    @Override
    public void updatesleeprule(UpdateSleepRuleDto updateSleepRuleDto) {
        if(updateSleepRuleDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(updateSleepRuleDto.getDeviceUniqueId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        if(updateSleepRuleDto.getId()==null){
            //新建
            GroupPullTaskDeviceConfig groupPullTaskDeviceConfig=new GroupPullTaskDeviceConfig();
            BeanUtil.copyProperties(updateSleepRuleDto,groupPullTaskDeviceConfig);
            groupPullTaskDeviceConfig.setRule(JSONObject.toJSONString(updateSleepRuleDto.getSleepRule()));
            groupPullTaskDeviceConfigMapper.addGroupSendTaskDeviceConfig(groupPullTaskDeviceConfig);
        }
        if(updateSleepRuleDto.getId()!=null){
            //修改
            GroupPullTaskDeviceConfig groupPullTaskDeviceConfig=  groupPullTaskDeviceConfigMapper.getById(updateSleepRuleDto.getId(),updateSleepRuleDto.getMerId());

            if(groupPullTaskDeviceConfig!=null){
                BeanUtil.copyProperties(updateSleepRuleDto,groupPullTaskDeviceConfig);
                groupPullTaskDeviceConfig.setRule(JSONObject.toJSONString(updateSleepRuleDto.getSleepRule()));
                groupPullTaskDeviceConfigMapper.update(groupPullTaskDeviceConfig);
            }
        }
    }

    @Override
    public void breakGroupPullJob(GroupPullJobDto groupPullJobDto) {
        if(groupPullJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupPullJob groupPullJob = groupPullJobMapper.getById(groupPullJobDto.getId(), groupPullJobDto.getMerId());
        if(groupPullJob==null||(groupPullJob.getStatus()!=null&&groupPullJob.getStatus().equals(3))){
            return;
        }
        groupPullJob.setStatus(3);
        groupPullJobMapper.update(groupPullJob);
    }

    @Override
    public void continueGroupPullJob(GroupPullJobDto groupPullJobDto) {
        if(groupPullJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        GroupPullJob groupPullJob = groupPullJobMapper.getById(groupPullJobDto.getId(), groupPullJobDto.getMerId());
        if(groupPullJob==null||(groupPullJob.getStatus()!=null&&groupPullJob.getStatus().equals(1))){
            return;
        }
        groupPullJob.setStatus(1);

        GroupPullJobDeviceQuery groupPullJobDeviceQuery=new GroupPullJobDeviceQuery();
        groupPullJobDeviceQuery.setMerId(groupPullJob.getMerId());
        groupPullJobDeviceQuery.setJobId(groupPullJob.getId());
        List<GroupPullJobDeviceVo> groupPullJobDeviceVoList=groupPullJobDeviceMapper.getGroupPullJobDeviceList(groupPullJobDeviceQuery);
        if(groupPullJobDeviceVoList!=null&&!groupPullJobDeviceVoList.isEmpty()){
            for (GroupPullJobDeviceVo groupPullJobDeviceVo:groupPullJobDeviceVoList) {
                try {
                    GroupPullJobMsgQuery groupPullJobMsgQuery=new GroupPullJobMsgQuery();
                    groupPullJobMsgQuery.setJobId(groupPullJobDeviceVo.getJobId());
                    groupPullJobMsgQuery.setDeviceUniqueId(groupPullJobDeviceVo.getDeviceUniqueId());
                    groupPullJobMsgQuery.setStatus(1);
                    groupPullJobMsgQuery.setMerId(groupPullJobDeviceVo.getMerId());
                    List<GroupPullJobMsgVo> groupPullJobMsgVoList=groupPullJobMsgMapper.getGroupPullJobMsgList(groupPullJobMsgQuery);
                    if(groupPullJobMsgVoList!=null&&!groupPullJobMsgVoList.isEmpty()){
                        for (GroupPullJobMsgVo groupPullJobMsgVo:groupPullJobMsgVoList) {
                            try {
                                GroupPullJobMsg groupPullJobMsg=new GroupPullJobMsg();
                                groupPullJobMsg.setId(groupPullJobMsgVo.getId());
                                groupPullJobMsg.setMerId(groupPullJobMsgVo.getMerId());
                                groupPullJobMsg.setDelay(Math.max((groupPullJobMsgVo.getDelay() - groupPullJobDeviceVo.getDelaySnapshot()), 0));
                                groupPullJobMsgMapper.update(groupPullJobMsg);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                //延迟发送快照数清零
                GroupPullJobDevice groupPullJobDevice=new GroupPullJobDevice();
                groupPullJobDevice.setId(groupPullJobDeviceVo.getId());
                groupPullJobDevice.setMerId(groupPullJobDeviceVo.getMerId());
                groupPullJobDevice.setDelaySnapshot(0);
                groupPullJobDeviceMapper.update(groupPullJobDevice);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        groupPullJobMapper.update(groupPullJob);
    }

    @Override
    public void cancelGroupPullJob(GroupPullJobDto groupPullJobDto) {
        if(groupPullJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupPullJob groupPullJob = groupPullJobMapper.getById(groupPullJobDto.getId(), groupPullJobDto.getMerId());
        if(groupPullJob==null||(groupPullJob.getStatus()!=null&&groupPullJob.getStatus().equals(4))){
            return;
        }
        groupPullJob.setStatus(4);
        groupPullJobMapper.update(groupPullJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delGroupPullJob(GroupPullJobDto groupPullJobDto) {

        if(groupPullJobDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupPullJobDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        GroupPullJob groupPullJob = groupPullJobMapper.getById(groupPullJobDto.getId(), groupPullJobDto.getMerId());
        if(groupPullJob==null){
            return;
        }

        GroupPullJobDeviceQuery groupPullJobDeviceQuery=new GroupPullJobDeviceQuery();
        groupPullJobDeviceQuery.setMerId(groupPullJob.getMerId());
        groupPullJobDeviceQuery.setJobId(groupPullJob.getId());
        List<GroupPullJobDeviceVo> groupPullJobDeviceList = groupPullJobDeviceMapper.getGroupPullJobDeviceList(groupPullJobDeviceQuery);
        if(groupPullJobDeviceList!=null&&!groupPullJobDeviceList.isEmpty()){
            groupPullJobDeviceList.forEach(item->groupPullJobDeviceMapper.delById(item.getId(),item.getMerId()));
        }

        GroupPullJobMsgQuery groupPullJobMsgQuery=new GroupPullJobMsgQuery();
        groupPullJobMsgQuery.setMerId(groupPullJob.getMerId());
        groupPullJobMsgQuery.setJobId(groupPullJob.getId());
        List<GroupPullJobMsgVo> groupPullJobMsgList = groupPullJobMsgMapper.getGroupPullJobMsgList(groupPullJobMsgQuery);
        if(groupPullJobMsgList!=null&&!groupPullJobMsgList.isEmpty()){
            groupPullJobMsgList.forEach(item2->groupPullJobMsgMapper.delById(item2.getId(),item2.getMerId()));
        }


        groupPullJobMapper.deleById(groupPullJob.getId(),groupPullJob.getMerId());
        }


    @Override
    public Object findAddFangetEffectuateGroupGroup(EffectuateGroupDto effectuateGroupDto) {
        if(effectuateGroupDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(effectuateGroupDto.getPlanId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(org.apache.commons.lang3.StringUtils.isBlank(effectuateGroupDto.getGroupPullKey())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        GroupPullTask groupPullTask = groupPullTaskMapper.getById(effectuateGroupDto.getPlanId(), effectuateGroupDto.getMerId());
        if(groupPullTask==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }
        if(org.apache.commons.lang3.StringUtils.isBlank(groupPullTask.getGuider())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案引导语不存在");
        }
        List<GroupPullData> groupPullDataList = JSONObject.parseArray(groupPullTask.getGuider(), GroupPullData.class);
        if(groupPullDataList==null||groupPullDataList.isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案引导语不存在");
        }
        List<EffectuateGroupVo> effectuateGroupVoList=new ArrayList<>();

        for (GroupPullData groupPullData:groupPullDataList) {
            if(groupPullData.getMsgType()!=null&&groupPullData.getMsgType().equals(100)){
                if(!org.apache.commons.lang3.StringUtils.isBlank(groupPullData.getGroupPullKey())&&groupPullData.getGroupPullKey().equals(effectuateGroupDto.getGroupPullKey())){

                    if(groupPullData.getGroupRules()!=null&&!groupPullData.getGroupRules().isEmpty()){
                        effectuateGroupVoList=new ArrayList<>();
                        for (GroupRule groupRule:groupPullData.getGroupRules()) {
                            EffectuateGroupVo effectuateGroupVo = new EffectuateGroupVo();
                            effectuateGroupVo.setDeviceId(groupRule.getDeviceId());
                            effectuateGroupVo.setDeviceUniqueId(groupRule.getDeviceUniqueId());
                            effectuateGroupVo.setDeviceName(groupRule.getDeviceName());
                            effectuateGroupVo.setDeviceHeadImageUrl(groupRule.getDeviceHeadImageUrl());
                            if(groupRule.getGroupRuleInfos()!=null&&!groupRule.getGroupRuleInfos().isEmpty()){
                                List<GroupRuleInfoVo> groupRuleInfoVoList=new ArrayList<>();
                                for (GroupRuleInfo groupRuleInfo:groupRule.getGroupRuleInfos()) {
                                    GroupRuleInfoVo groupRuleInfoVo = new GroupRuleInfoVo();
                                    groupRuleInfoVo.setDeviceId(groupRule.getDeviceId());
                                    groupRuleInfoVo.setDeviceUniqueId(groupRule.getDeviceUniqueId());
                                    groupRuleInfoVo.setDeviceName(groupRule.getDeviceName());
                                    groupRuleInfoVo.setGroupId(groupRuleInfo.getGroupId());
                                    groupRuleInfoVo.setGroupWxid(groupRuleInfo.getGroupWxid());
                                    groupRuleInfoVo.setGroupNick(groupRuleInfo.getGroupNick());
                                    groupRuleInfoVo.setGenders(groupRuleInfo.getGenders());
                                    groupRuleInfoVo.setDeviceHeadImageUrl(groupRule.getDeviceHeadImageUrl());
                                    groupRuleInfoVo.setGroupMemberNum((Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(),groupRuleInfo.getGroupWxid())));
                                    groupRuleInfoVoList.add(groupRuleInfoVo);
                                }
                                effectuateGroupVo.setGroupRuleInfoVoList(groupRuleInfoVoList);
                            }
                            effectuateGroupVoList.add(effectuateGroupVo);
                        }

                    }
                }
            }
        }

        return effectuateGroupVoList;
    }
}
